/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Update;

import functions.Dogy;
import functions.LogError;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 *
 * @author JArik
 */
public class DUpdater {

    public static void checkOnlineUpdate(String domenPath)
    {
        try {
        String dataToSend = "prefix="+Dogy.V_PREFIX+"&version="+Dogy.VERSION;
        URL update = new URL(domenPath+"/checkRelease.php");
        URLConnection updateConnection = update.openConnection();
        Dogy.incrLoadingProgress(10,"updateCheck","Подключение...");
        updateConnection.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(updateConnection.getOutputStream());
        wr.write(dataToSend);
        wr.flush();
        wr.close();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                updateConnection.getInputStream(),"UTF-8"));
        String inputLine;

        double downloaded = 0;
        double perc =0;
        while ((inputLine = in.readLine()) != null)
        {
                if(!inputLine.isEmpty() && !inputLine.equals("error"))
                {
                    Dogy.NEW_VERSION_READY = true;
                    URL download = new URL(domenPath+"/"+inputLine);
                    URLConnection downConnection = download.openConnection();
                    downConnection.connect();

                    FileOutputStream fos = new FileOutputStream("update.jar");
                    BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
                    BufferedInputStream bin = new BufferedInputStream(downConnection.getInputStream());

                    byte data[] = new byte[1024];
                    int count = 0;
                    while((count = bin.read(data,0,1023))>= 0)
                    {
                        bout.write(data,0,count);
                        downloaded+=count;
                        perc = downloaded/(double)downConnection.getContentLength();
                        Dogy.incrLoadingProgress((int) (10 + (80 * perc)),"updateCheck","Скачивание... "+(int)(perc*100));
                    }
                    Dogy.incrLoadingProgress(95,"updateCheck","Сохранение...");
                    bin.close();
                    bout.close();
                    fos.close();
                    Dogy.NEW_VERSION_READY = true;
                }
        }

        Dogy.incrLoadingProgress(100,"updateCheck","Завершение...");
        in.close();
        } catch(Exception e)
        {
            LogError.reportSilentError(e);
            e.printStackTrace();
        }
    }
}
